package ynu.edu.elmspringboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ynu.edu.elmspringboot.mapper.CartMapper;
import ynu.edu.elmspringboot.mapper.OrdersMapper;
import ynu.edu.elmspringboot.mapper.BusinessMapper;
import ynu.edu.elmspringboot.mapper.OrderDetailetMapper;
import ynu.edu.elmspringboot.po.Cart;
import ynu.edu.elmspringboot.po.Orders;
import ynu.edu.elmspringboot.po.Business;
import ynu.edu.elmspringboot.po.OrderDetailet;
import ynu.edu.elmspringboot.service.OrdersService;

import java.util.List;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private BusinessMapper businessMapper;

    @Autowired
    private OrderDetailetMapper orderDetailetMapper;

    @Autowired
    private CartMapper cartMapper;

    @Override
    public Orders getOrdersWithBusinessAndOrderDetailets(Integer orderId) {
        Orders orders = ordersMapper.selectById(orderId);
        if (orders != null) {
            Business business = businessMapper.selectById(orders.getBusinessId());
            List<OrderDetailet> orderDetailets = orderDetailetMapper.selectList(
                    new QueryWrapper<OrderDetailet>().eq("order_id", orderId)
            );
            orders.setBusiness(business);
            orders.setList(orderDetailets);
        }
        return orders;
    }

    @Override
    @Transactional
    public boolean updateAndDeleteCart(Integer orderId, Integer orderState) {
        Orders orders = ordersMapper.selectById(orderId);

        if (orders != null) {
            //更新订单支付状态
            orders.setOrderState(orderState);
            ordersMapper.updateById(orders);

            //查询支付成功的订单，删除相应的购物车记录
            List<Orders> ordersList = ordersMapper.selectList(new QueryWrapper<Orders>().eq("order_id", orderId).eq("order_state", 1));

            ordersList.forEach(order -> {
                List<Cart> cartList = cartMapper.selectList(new QueryWrapper<Cart>().eq("order_id", order.getOrderId()));
                cartList.forEach(cart -> {
                    cartMapper.deleteById(cart);
                });
            });


            return true;
        } else {
            return false;
        }

    }
}